package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.node.LongNode;
import com.mysql.cj.protocol.ResultsetRow;
import com.xmy.cultivate.annotaion.RepeatSubmit;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.IncomeDayReport;
import com.xmy.cultivate.entity.views.MelodyConfirm;
import com.xmy.cultivate.entity.views.SchedulingClash;
import com.xmy.cultivate.entity.views.face.FaceGetScheduling;
import com.xmy.cultivate.enums.ReachTypeEnum;
import com.xmy.cultivate.enums.StatusRecordEnum;
import com.xmy.cultivate.enums.StatusSchedulingEnum;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.service.impl.RepairCourseServiceImpl;
import com.xmy.cultivate.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.util.StringUtil;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.support.SimpleTriggerContext;
import org.springframework.web.bind.annotation.*;

import java.rmi.MarshalledObject;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 补课表 前端控制器
 * </p>
 *
 * @author Coly
 * @since 2023-03-07
 */
@RestController
@RequestMapping("/api/repairCourse")
@Api(tags = "补课表")
@Scope("prototype")
public class RepairCourseController extends BaseController {
    @Autowired
    IRepairCourseService iRepairCourseServicel;
    @Autowired
    ICourseSchedulingDetailService iCourseSchedulingDetailService;

    @Autowired
    CourseSchedulingDetailMapper courseSchedulingDetailMapper;

    @Autowired
    RepairCourseMapper repairCourseMapper;

    @Autowired
    RecordCourseMapper recordCourseMapper;

    @Autowired
    GradeMapper gradeMapper;

    @Autowired
    IStudentService iStudentService;

    @Autowired
    ILackCourseLogService iLackCourseLogService;

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    ICourseSchedulingClashService iCourseSchedulingClashService;

    @Autowired
    IRepairCourseService iRepairCourseService;

    @Autowired
    IRecordCourseService iRecordCourseService;

    @Autowired
    IOrderDetailService iOrderDetailService;

    @Autowired
    HolidayMapper holidayMapper;

    @Autowired
    IdWorker idWorker;

    @Autowired
    ICompanyService iCompanyService;

    @Autowired
    IStudentGradeService iStudentGradeService;

    @Autowired
    IRecordBackDateSetService iRecordBackDateSetService;


    /**
     * 根据班级检索排课记录
     *
     * @param reMap
     * @param gradeId
     * @return
     */
    @ApiOperation(" 根据班级检索排课记录")
    @GetMapping("selectScheuling")
    public Result selectScheuling(@RequestParam Map<String, String> reMap,
                                  @RequestParam(value = "gradeId", required = false) String gradeId) {
        Integer pageNum = StringUtils.isEmpty(reMap.get("pageNum")) ? 1 : Integer.valueOf(reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty(reMap.get("pageSize")) ? 10 : Integer.valueOf(reMap.get("pageSize"));

        String schoolId = reMap.get("schoolId");
        IPage<CourseSchedulingDetail> page = new Page<>(pageNum, pageSize);
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(schoolId), "school_id", schoolId);
        queryWrapper.eq(StringUtils.isNotBlank(gradeId), "grade_id", gradeId);
        queryWrapper.eq("deleted", 0);
        LocalDate nowDate = LocalDate.now();
        queryWrapper.ge("start_date_time", nowDate);
        iCourseSchedulingDetailService.getListByClassId(page, queryWrapper);
        return new Result(Code.OK, new PageResult(page.getRecords(), page.getTotal(), page.getPages()), "");
    }

    /**
     * 根据排课id插入(插班补课)
     *
     * @return
     */
    @PostMapping("insertByCouorseScheulingId")
    @RepeatSubmit(expireSeconds = 30)
    public Result insertByCouorseScheulingId(@RequestBody Map reMap) {
        Quarter quarter = iQuarterService.getNowQuarter();
        String schedulingId = (String) reMap.get("schedulingId");
        List<String> recordCourseIds = (List<String>) reMap.get("recordCourseIds");

        //是否允许提交
        boolean isAction = true;
        StringBuilder stringBuilderError = new StringBuilder();
        StringBuilder stringBuilderRight = new StringBuilder();
        String lessonType = "";
        CourseSchedulingDetail courseSchedulingDetail = courseSchedulingDetailMapper.selectById(schedulingId);

        for (String ids : recordCourseIds) {
            Long id = Long.parseLong(ids);
            RecordCourse recordCourse = recordCourseMapper.selectById(id);

            if (recordCourse.getStatus().getKey() == 1) {
                isAction = false;
                stringBuilderError.append(recordCourse.getStudentName()).append(":已经到课，不能补课,");
                continue;
            }
            if (recordCourse.getIsRepair() == 1) {
                isAction = false;
                stringBuilderError.append(recordCourse.getStudentName()).append(":已经补课,");
                continue;
            }
            if (recordCourse.getIsRepair() == 2) {
                //已排课但是超时未补课
                if (recordCourse.getRepairEndDateTime().isAfter(LocalDateTime.now())) {
                    isAction = false;
                    stringBuilderError.append(recordCourse.getStudentName()).append(":已经安排补课,");
                    continue;
                }
            }
            if (recordCourse.getRepairId() != null) {
                RepairCourse repairCourse = iRepairCourseService.getById(recordCourse.getRepairId());
                if (repairCourse != null) {
                    //是否已经补课
                    if (repairCourse.getIsSignIn().equals(1)) {
                        RecordCourse recordCourseNew = recordCourseMapper.selectOne(new QueryWrapper<RecordCourse>().eq("scheduling_detail_id", repairCourse.getId()).last("limit 1"));
                        if (recordCourseNew != null) {
                            isAction = false;
                            stringBuilderError.append(recordCourse.getStudentName()).append(":已补课,");
                            continue;
                        }
                    }
                }
            }


            Long repairId = idWorker.nextId();
            Grade grade = gradeMapper.selectById(courseSchedulingDetail.getGradeId());

            List<SchedulingClash> schedulingClashList = iCourseSchedulingDetailService.schedulingClash(grade.getYearPart(), grade.getQuarterNum(), grade.getSchoolId(), recordCourse.getStudentId().toString(), courseSchedulingDetail.getStartDateTime().toString(), courseSchedulingDetail.getEndDateTime().toString(), "1", "");
            StringBuilder studentClashBuilder = new StringBuilder();
            for (SchedulingClash schedulingClash : schedulingClashList) {
                String schoolTime = schedulingClash.getTimeStart() + "-" + schedulingClash.getTimeEnd();
                String courseTypeName = CommonUtil.getCourseTypeName(schedulingClash.getCourseType());
                studentClashBuilder.append(schedulingClash.getStudentName()).append("与").append(courseTypeName).append(schoolTime);
                if (StringUtils.isNotBlank(schedulingClash.getGradeName())) {
                    studentClashBuilder.append(",").append(schedulingClash.getGradeName());
                }
                studentClashBuilder.append("存在时间冲突");
                studentClashBuilder.append("；");
            }
            String studentClash = studentClashBuilder.toString();
            if (StringUtils.isNotBlank(studentClash)) {
                return new Result(Code.ERROR, "", studentClash);
            }
            //3安排请假补课，6安排缺课补课
            Integer repairType = 3;
            iRepairCourseServicel.insertTo(Long.parseLong(schedulingId), id, repairType, repairId, recordCourse.getLessonNum());
            stringBuilderRight.append(recordCourse.getStudentName()).append("安排成功，");
        }
        if (isAction == false) {
            return new Result(Code.ERROR, null, stringBuilderRight.toString() + "" + stringBuilderError.toString());
        }

        return new Result(Code.OK, "", stringBuilderRight.toString());
    }

    /**
     * 新增补课记录（按日程补课）
     *
     * @return
     * @throws ParseException
     */
    @PostMapping("insertRepair")
    @RepeatSubmit(expireSeconds = 30)
    public Result insertRepair(@RequestBody Map reMap) throws ParseException {
        Long gradeId = null;
        if (reMap.get("gradeId") != null) {
            gradeId = Long.parseLong((String) reMap.get("gradeId"));
        }
        Long teacherId = null;
        if (reMap.get("teacherId") != null) {
            teacherId = Long.parseLong((String) reMap.get("teacherId"));
        }

        String schooleDate = (String) reMap.get("schooleDate");
        String timeStart = (String) reMap.get("timeStart");
        String timeEnd = (String) reMap.get("timeEnd");
        List<String> recordCourseIds = (List<String>) reMap.get("recordCourseIds");

        //Grade grade = gradeMapper.selectById(gradeId);

        String lessonType = "";//为空表示所有类型

        String startDateTime = schooleDate + " " + timeStart + ":00";
        String endDateTime = schooleDate + " " + timeEnd + ":00";

        //是否允许提交
        boolean isAction = true;

        StringBuilder stringBuilderError = new StringBuilder();
        StringBuilder stringBuilderRight = new StringBuilder();

        Integer yearPart = null;
        Integer quarterNum = null;

        for (String ids : recordCourseIds) {
            Long repairId = idWorker.nextId();
            RecordCourse recordCourse = recordCourseMapper.selectById(Long.parseLong(ids));
            if (recordCourse.getIsRepair() == 1) {
                //已补课
                isAction = false;
                stringBuilderError.append(recordCourse.getStudentName()).append(":已补课,");
                continue;
            } else if (recordCourse.getIsRepair() == 2) {
                //该学生是否已经安排补课
                if (recordCourse.getRepairEndDateTime().isAfter(LocalDateTime.now())) {
                    //判断当前时间该班级是否已有排课
                    isAction = false;
                    stringBuilderError.append(recordCourse.getStudentName()).append(":已安排补课,");
                    continue;
                }
            }
            if (recordCourse.getSchoolDate().isAfter(LocalDate.parse("2024-11-24"))) {
                Quarter quarterNow = iQuarterService.getNowQuarter();

                //学期班
                if (quarterNow.getType().equals(1)) {
                    QueryWrapper<RecordBackDateSet> recordBackDateSetQueryWrapper = new QueryWrapper<>();
                    recordBackDateSetQueryWrapper.eq("record_course_id", recordCourse.getId());
                    recordBackDateSetQueryWrapper.last("limit 1");
                    RecordBackDateSet recordBackDateSet = iRecordBackDateSetService.getOne(recordBackDateSetQueryWrapper);
                    if (Objects.isNull(recordBackDateSet)) {
                        //下周日
                        LocalDate nextSunday = recordCourse.getSchoolDate().with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)).plusWeeks(1);
                        if (LocalDate.now().isAfter(nextSunday)){
                            isAction = false;
                            stringBuilderError.append(recordCourse.getStudentName()).append(":已超时，不能按排补课");
                            continue;
                        }
                        if (LocalDate.parse(schooleDate).isAfter(nextSunday)) {
                            isAction = false;
                            stringBuilderError.append(recordCourse.getStudentName()).append(":安排的补课时间不能大于" + nextSunday);
                            continue;
                        }
                    }else {
                        if (LocalDate.now().isAfter(recordBackDateSet.getBackDate()) || LocalDate.now().equals(recordBackDateSet.getBackDate())){
                            isAction = false;
                            stringBuilderError.append(recordCourse.getStudentName()).append(":已超时，不能按排补课");
                            continue;
                        }
                        if (LocalDate.parse(schooleDate).isAfter(recordBackDateSet.getBackDate())) {
                            isAction = false;
                            stringBuilderError.append(recordCourse.getStudentName()).append(":安排的补课时间不能大于" + recordBackDateSet.getBackDate());
                            continue;
                        }
                    }
                }
            }


            //是否已经补课
            if (recordCourse.getRepairId() != null) {
                RepairCourse repairCourse = iRepairCourseService.getById(recordCourse.getRepairId());
                if (repairCourse != null) {
                    //是否已经补课
                    if (repairCourse.getIsSignIn().equals(1)) {
                        RecordCourse recordCourseNew = recordCourseMapper.selectOne(new QueryWrapper<RecordCourse>().eq("scheduling_detail_id", repairCourse.getId()).last("limit 1"));
                        if (recordCourseNew != null) {
                            isAction = false;
                            stringBuilderError.append(recordCourse.getStudentName()).append(":已补课,");
                            continue;
                        }
                    }
                }
            }

            StringBuilder studentClashBuilder = new StringBuilder();

            // 查询是否当天已经安排补课信息
            if (!this.adminId.equals(1568138350324350975L)) {
                Company company = iCompanyService.getById(1L);
                if (company.getIsMakeUpOne().equals(1)) {
                    QueryWrapper wrapper = new QueryWrapper<>();
                    wrapper.eq("year_part", recordCourse.getYearPart());
                    wrapper.eq("quarter", recordCourse.getQuarter());
                    wrapper.eq("student_id", recordCourse.getStudentId());
                    wrapper.inSql("course_type", "3,6");
                    wrapper.apply("(end_date_time >= NOW() OR is_sign_in = 1)");
                    wrapper.eq("school_date", schooleDate);
                    wrapper.eq("subjects_id", recordCourse.getSubjectsId());
                    wrapper.eq("lesson_type", 1);
                    Long count = iRepairCourseService.count(wrapper);
                    if (count > 0L) {
                        isAction = false;
                        studentClashBuilder.append(recordCourse.getStudentName()).append(schooleDate + " 已安排过补课，每个科目一天只能安排一次精品课的补课，请勿再次安排！");
                        continue;
                    }
                }
            }

            //与精品课冲突
            List<SchedulingClash> schedulingClashList = iCourseSchedulingDetailService.schedulingClash(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getSchoolId(), recordCourse.getStudentId().toString(), startDateTime, endDateTime, "1", "");
            for (SchedulingClash schedulingClash : schedulingClashList) {
                String schoolTime = schedulingClash.getTimeStart() + "-" + schedulingClash.getTimeEnd();
                String courseTypeName = CommonUtil.getCourseTypeName(schedulingClash.getCourseType());
                studentClashBuilder.append(schedulingClash.getStudentName()).append("与").append(courseTypeName).append(schoolTime);
                if (StringUtils.isNotBlank(schedulingClash.getGradeName())) {
                    studentClashBuilder.append(",").append(schedulingClash.getGradeName());
                }
                studentClashBuilder.append("存在时间冲突");
                studentClashBuilder.append("；");
            }

            String studentClash = studentClashBuilder.toString();
            if (StringUtils.isNotBlank(studentClash)) {
                return new Result(Code.ERROR, "", studentClash);
            }

            stringBuilderRight.append(recordCourse.getStudentName()).append("安排成功，");
            //3安排请假补课，6安排缺课补课
            Integer repairType = 3;
            iRepairCourseServicel.insertIn(gradeId, teacherId, Long.parseLong(ids), schooleDate, timeStart, timeEnd, repairType, repairId, recordCourse.getLessonNum());
        }
        if (isAction == false) {
            return new Result(Code.ERROR, null, stringBuilderError.toString());
        }

        return new Result(Code.OK, "", "");
    }


    /**
     * 根据排课id插入,添加缺课补课（插班补课）
     *
     * @return
     */
    @PostMapping("insertByCourseScheulingIdForLack")
    @RepeatSubmit(expireSeconds = 30)
    public Result insertByCourseScheulingIdForLack(@RequestBody Map reMap) {
        Quarter quarter = iQuarterService.getNowQuarter();

        String schedulingId = (String) reMap.get("schedulingId");
        List<String> recordCourseIds = (List<String>) reMap.get("recordCourseIds");
        //是否允许提交
        boolean isAction = true;
        StringBuilder stringBuilderError = new StringBuilder();
        StringBuilder stringBuilderRight = new StringBuilder();
        String lessonType = "";
        CourseSchedulingDetail courseSchedulingDetail = courseSchedulingDetailMapper.selectById(schedulingId);
        for (String ids : recordCourseIds) {
            Long id = Long.parseLong(ids);
            LackCourseLog lackCourseLog = iLackCourseLogService.getById(ids);
            Student student = iStudentService.getById(lackCourseLog.getStudentId());

            if (lackCourseLog.getStatus() == 1) {
                isAction = false;
                stringBuilderError.append(student.getName()).append(":已经到课，不能补课,");
                continue;
            }
            if (lackCourseLog.getIsRepair() == 1) {
                isAction = false;
                stringBuilderError.append(student.getName()).append(":已经补课,");
                continue;
            }
            if (lackCourseLog.getIsRepair() == 2) {
                //已排课但是超时未补课
                if (lackCourseLog.getRepairEndDateTime().isAfter(LocalDateTime.now())) {
                    isAction = false;
                    stringBuilderError.append(student.getName()).append(":已经安排补课,");
                    continue;
                }
            }

            if (lackCourseLog.getRepairId() != null) {
                RepairCourse repairCourse = iRepairCourseService.getById(lackCourseLog.getRepairId());
                if (repairCourse != null) {
                    //是否已经补课
                    if (repairCourse.getIsSignIn().equals(1)) {
                        RecordCourse recordCourseNew = recordCourseMapper.selectOne(new QueryWrapper<RecordCourse>().eq("scheduling_detail_id", repairCourse.getId()).last("limit 1"));
                        if (recordCourseNew != null) {
                            isAction = false;
                            stringBuilderError.append(student.getName()).append(":已补课,");
                            continue;
                        }
                    }
                }
            }

            Long repairId = idWorker.nextId();
            //精品课
            Grade grade = gradeMapper.selectById(courseSchedulingDetail.getGradeId());
            List<SchedulingClash> schedulingClashList = iCourseSchedulingDetailService.schedulingClash(grade.getYearPart(), grade.getQuarterNum(), grade.getSchoolId(), student.getId().toString(), courseSchedulingDetail.getStartDateTime().toString(), courseSchedulingDetail.getEndDateTime().toString(), "1", "");
            StringBuilder studentClashBuilder = new StringBuilder();
            for (SchedulingClash schedulingClash : schedulingClashList) {
                String schoolTime = schedulingClash.getTimeStart() + "-" + schedulingClash.getTimeEnd();
                String courseTypeName = CommonUtil.getCourseTypeName(schedulingClash.getCourseType());
                studentClashBuilder.append(schedulingClash.getStudentName()).append("与").append(courseTypeName).append(schoolTime);
                if (StringUtils.isNotBlank(schedulingClash.getGradeName())) {
                    studentClashBuilder.append(",").append(schedulingClash.getGradeName());
                }
                studentClashBuilder.append("存在时间冲突");
                studentClashBuilder.append("；");
            }
            String studentClash = studentClashBuilder.toString();
            if (StringUtils.isNotBlank(studentClash)) {
                return new Result(Code.ERROR, "", studentClash);
            }

            //3安排请假补课，6安排缺课补课
            Integer repairType = 6;
            iRepairCourseServicel.insertTo(Long.parseLong(schedulingId), id, repairType, repairId, lackCourseLog.getNum());
            stringBuilderRight.append(student.getName()).append("安排成功，");
        }
        if (isAction == false) {
            return new Result(Code.ERROR, null, stringBuilderRight.toString() + "" + stringBuilderError.toString());
        }

        return new Result(Code.OK, "", stringBuilderRight.toString());
    }

    /**
     * 新增缺课补课（按日程补课）
     *
     * @return
     * @throws ParseException
     */
    @PostMapping("insertRepairForLack")
    @RepeatSubmit(expireSeconds = 30)
    public Result insertRepairForLack(@RequestBody Map reMap) throws ParseException {

        Quarter quarter = iQuarterService.getNowQuarter();

        Long gradeId = null;
        if (reMap.get("gradeId") != null) {
            gradeId = Long.parseLong((String) reMap.get("gradeId"));
        }

        String schooleDate = (String) reMap.get("schooleDate");
        String timeStart = (String) reMap.get("timeStart");
        String timeEnd = (String) reMap.get("timeEnd");
        Long teacherId = null;
        if (reMap.get("teacherId") != null) {
            teacherId = Long.parseLong((String) reMap.get("teacherId"));
        }


        LocalDateTime startDateTime = LocalDateTime.parse(schooleDate + "T" + timeStart + ":00");
        LocalDateTime endDateTime = LocalDateTime.parse(schooleDate + "T" + timeEnd + ":00");
        if (startDateTime.isAfter(endDateTime)) {
            return new Result(Code.ERROR, null, "结束时间小于开始时间");
        }

        List<String> recordCourseIds = (List<String>) reMap.get("recordCourseIds");

        //Grade grade = gradeMapper.selectById(gradeId);

        //是否允许提交
        boolean isAction = true;

        StringBuilder stringBuilderError = new StringBuilder();
        StringBuilder stringBuilderRight = new StringBuilder();

        String lessonType = "";//查所有类型为空

        for (String ids : recordCourseIds) {
            Long lackCourseLogId = Long.parseLong(ids);
            Long repairId = idWorker.nextId();
            LackCourseLog lackCourseLog = iLackCourseLogService.getById(lackCourseLogId);
            Student student = iStudentService.getById(lackCourseLog.getStudentId());
            if (lackCourseLog.getIsRepair() == 1) {
                //已补课
                isAction = false;
                stringBuilderError.append(student.getName()).append(":已补课,");
                continue;
            } else if (lackCourseLog.getIsRepair() == 2) {
                //该学生是否已经安排补课
                if (lackCourseLog.getRepairEndDateTime().isAfter(LocalDateTime.now())) {
                    //判断当前时间该班级是否已有排课
                    isAction = false;
                    stringBuilderError.append(student.getName()).append(":已安排补课,");
                    continue;
                }
            }

            if (lackCourseLog.getRepairId() != null) {
                RepairCourse repairCourse = iRepairCourseService.getById(lackCourseLog.getRepairId());
                if (repairCourse != null) {
                    //是否已经补课
                    if (repairCourse.getIsSignIn().equals(1)) {
                        RecordCourse recordCourseNew = recordCourseMapper.selectOne(new QueryWrapper<RecordCourse>().eq("scheduling_detail_id", repairCourse.getId()).last("limit 1"));
                        if (recordCourseNew != null) {
                            isAction = false;
                            stringBuilderError.append(student.getName()).append(":已补课,");
                            continue;
                        }
                    }
                }
            }

            List<SchedulingClash> schedulingClashList = iCourseSchedulingDetailService.schedulingClash(lackCourseLog.getYearPart(), lackCourseLog.getQuarterNum(), lackCourseLog.getSchoolId(), student.getId().toString(), startDateTime.toString(), endDateTime.toString(), "1", "");

            StringBuilder studentClashBuilder = new StringBuilder();

            if (!this.adminId.equals(1568138350324350975L)) {
                Company company = iCompanyService.getById(1L);
                if (company.getIsMakeUpOne().equals(1)) {
                    // 查询是否当天已经安排补课信息
                    QueryWrapper wrapper = new QueryWrapper<>();
                    wrapper.eq("year_part", lackCourseLog.getYearPart());
                    wrapper.eq("quarter", lackCourseLog.getQuarterNum());
                    wrapper.eq("student_id", lackCourseLog.getStudentId());
                    wrapper.inSql("course_type", "3,6");
                    wrapper.apply("(end_date_time >= NOW() OR is_sign_in = 1)");
                    wrapper.eq("subjects_id", lackCourseLog.getSubjectsId());
                    wrapper.eq("lesson_type", 1);
                    wrapper.eq("school_date", schooleDate);
                    Long count = iRepairCourseService.count(wrapper);
                    if (count > 0L) {
                        isAction = false;
                        stringBuilderError.append(student.getName()).append(schooleDate + " 已安排过补课，每个科目一天只能安排一次精品课的补课，请勿再次安排！");
                        continue;
                    }
                }
            }
            for (SchedulingClash schedulingClash : schedulingClashList) {
                String schoolTime = schedulingClash.getTimeStart() + "-" + schedulingClash.getTimeEnd();
                String courseTypeName = CommonUtil.getCourseTypeName(schedulingClash.getCourseType());
                studentClashBuilder.append(schedulingClash.getStudentName()).append("与").append(courseTypeName).append(schoolTime);
                if (StringUtils.isNotBlank(schedulingClash.getGradeName())) {
                    studentClashBuilder.append(",").append(schedulingClash.getGradeName());
                }
                studentClashBuilder.append("存在时间冲突");
                studentClashBuilder.append("；");
            }
            String studentClash = studentClashBuilder.toString();
            if (StringUtils.isNotBlank(studentClash)) {
                return new Result(Code.ERROR, "", studentClash);
            }
            stringBuilderRight.append(student.getName()).append("安排成功，");
            //3安排请假补课，6安排缺课补课
            Integer repairType = 6;
            iRepairCourseServicel.insertIn(gradeId, teacherId, lackCourseLogId, schooleDate, timeStart, timeEnd, repairType, repairId, lackCourseLog.getLessonNum());
        }
        if (isAction == false) {
            return new Result(Code.ERROR, null, stringBuilderError.toString());
        }

        return new Result(Code.OK, "", "");
    }


    /**
     * 删除补课记录
     *
     * @param recordCourseID
     * @return
     */
    @DeleteMapping("/deleteRepair/{recordCourseID}")
    public Result deleteRepair(@PathVariable(value = "recordCourseID") Long recordCourseID) {
        RecordCourse recordCourse = recordCourseMapper.select(recordCourseID);
        if (recordCourse.getIsRepair() == 1) {
            return new Result(Code.ERROR, null, recordCourse.getStudentName() + "已经补课");
        }

        RepairCourse repairCourse = iRepairCourseService.getById(recordCourse.getRepairId());
        if (repairCourse != null) {
            //是否已经补课
            if (repairCourse.getIsSignIn().equals(1)) {
                RecordCourse recordCourseNew = recordCourseMapper.selectOne(new QueryWrapper<RecordCourse>().eq("scheduling_detail_id", repairCourse.getId()).last("limit 1"));
                if (recordCourseNew != null) {
                    return new Result(Code.ERROR, null, recordCourse.getStudentName() + "已经补课");
                }
            }
        }

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("record_course_id", recordCourseID);
        repairCourseMapper.delete(queryWrapper);
        recordCourse.setRepairId(0L);
        recordCourse.setIsRepair(0);
        recordCourseMapper.updateById(recordCourse);
        return new Result(Code.OK);
    }


    /**
     * 按班级调课前确认
     *
     * @return
     */
    @PostMapping("/melodyCourseForGradeConfirm")
    public Result melodyCourseForGradeConfirm(@RequestBody CourseSchedulingDetail courseSchedulingDetail) throws ParseException {
        CourseSchedulingDetail courseSchedulingDetailInfo = iCourseSchedulingDetailService.getById(courseSchedulingDetail.getId());

        if (courseSchedulingDetailInfo.getLessonType().equals(2) || courseSchedulingDetailInfo.getLessonType().equals(3)) {
            //非超级管理员刷题班、智能课，只能往前调课
            if (!this.adminId.equals(1568138350324350975L)) {
                // 判断排课时间是否已经超过原本的排课时间
                if (courseSchedulingDetail.getSchoolDate().isAfter(courseSchedulingDetailInfo.getSchoolDate()) || (courseSchedulingDetail.getSchoolDate().isEqual(courseSchedulingDetailInfo.getSchoolDate()) && courseSchedulingDetail.getTimeStart().compareTo(courseSchedulingDetailInfo.getTimeStart()) >= 0)) {
                    // return new Result(Code.ERROR, "", "上课时间不能大于调出课程的上课时间");
                }
            }
        }

        MelodyConfirm melodyConfirm = iRepairCourseServicel.melodyCourseForGradeConfirm(courseSchedulingDetail, courseSchedulingDetailInfo, this.adminId);
        return new Result(Code.OK, melodyConfirm, "");
    }

    /**
     * 按班级调课
     *
     * @return
     */
    @PostMapping("/melodyCourseForGrade")
    @RepeatSubmit(expireSeconds = 30)
    public Result melodyCourseForGrade(@RequestBody CourseSchedulingDetail courseSchedulingDetail) throws ParseException {
        //Long id = courseSchedulingDetailParam.getId();

        CourseSchedulingDetail courseSchedulingDetailInfo = iCourseSchedulingDetailService.getById(courseSchedulingDetail.getId());

        if (courseSchedulingDetailInfo == null) {
            return new Result(Code.ERROR, "", "被调课的数据不存在");
        }
        if (courseSchedulingDetailInfo.getStatus().equals(StatusSchedulingEnum.ON)) {
            return new Result(Code.ERROR, "", "该排班已记录，不能调整");
        }

        MelodyConfirm melodyConfirm = iRepairCourseServicel.melodyCourseForGradeConfirm(courseSchedulingDetail, courseSchedulingDetailInfo, this.adminId);
        if (melodyConfirm.getStatus().equals(0)) {
            return new Result(Code.ERROR, melodyConfirm, melodyConfirm.getMsg());
        }

        QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
        recordCourseQueryWrapper.eq("scheduling_detail_id", courseSchedulingDetailInfo.getId());
        List<RecordCourse> recordCourseList = recordCourseMapper.selectList(recordCourseQueryWrapper);
        /*if (rsCount > 0) {
            return new Result(Code.ERROR, "", "该排班已有学生签到，不能调整");
        }*/

        List<String> rsStuNameList = new ArrayList<>();
        for (RecordCourse recordCourse : recordCourseList) {
            String statusStr = "已签到";
            if (recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                statusStr = "已到课";
            } else if (recordCourse.getStatus().equals(StatusRecordEnum.LEAVE)) {
                statusStr = "已请假";
            } else if (recordCourse.getStatus().equals(StatusRecordEnum.Truancy)) {
                statusStr = "已旷课";
            }
            rsStuNameList.add(recordCourse.getStudentName() + statusStr);
        }
        if (rsStuNameList.size() > 0) {
            return new Result(Code.ERROR, "", "该排班已有" + String.join(",", rsStuNameList) + "不能调课");
        }


        if (courseSchedulingDetailInfo.getLessonType().equals(2) || courseSchedulingDetailInfo.getLessonType().equals(3)) {
            //非超级管理员刷题班、智能课，只能往前调课
            if (!adminId.equals(1568138350324350975L)) {
                // 判断排课时间是否已经超过原本的排课时间
                if (courseSchedulingDetail.getSchoolDate().isAfter(courseSchedulingDetailInfo.getSchoolDate()) || (courseSchedulingDetail.getSchoolDate().isEqual(courseSchedulingDetailInfo.getSchoolDate()) && courseSchedulingDetail.getTimeStart().compareTo(courseSchedulingDetailInfo.getTimeStart()) >= 0)) {
                    // return new Result(Code.ERROR, "", "上课时间不能大于调出课程的上课时间");
                }
            }
        }

        //courseSchedulingDetail.getId();
        //courseSchedulingDetail.getSchoolDate();
        //courseSchedulingDetail.getTimeStart();
        //courseSchedulingDetail.getTimeEnd();

        String startDateTime = courseSchedulingDetail.getSchoolDate() + "T" + courseSchedulingDetail.getTimeStart() + ":00";
        String endDateTime = courseSchedulingDetail.getSchoolDate() + "T" + courseSchedulingDetail.getTimeEnd() + ":00";

        LocalDateTime dateTimeNow = LocalDateTime.now().withNano(0);
        LocalDateTime endDateTimeFormat = LocalDateTime.parse(endDateTime);
        if (endDateTimeFormat.isBefore(dateTimeNow)) {
            return new Result(Code.ERROR, "", "下课时间不能小于当前时间");
        }

        if (melodyConfirm.getType().equals(1)) {
            courseSchedulingDetail.setUseLeaveNum(1);
        }


        Long count = iRepairCourseServicel.getClashCountForGrade(startDateTime, endDateTime, courseSchedulingDetail.getSchoolDate().toString(), courseSchedulingDetailInfo.getGradeId(), courseSchedulingDetailInfo.getId());
        //Long endCount = iRepairCourseServicel.getClashCountForGrade(endDateTime,endDateTime,courseSchedulingDetail.getSchoolDate().toString(),courseSchedulingDetailInfo.getGradeId(),courseSchedulingDetailInfo.getId());

        if (count.compareTo(0L) > 0) {
            return new Result(Code.ERROR, "", "存在时间冲突保存失败");
        }

        iRepairCourseServicel.melodyCourseForGrade(courseSchedulingDetail);
        return new Result(Code.OK, "", "");
    }

    /**
     * 删除按班级调课
     *
     * @return
     */
    @DeleteMapping("/deleteMelodyCourseForGrade/{id}")
    public Result deleteMelodyCourseForGrade(@PathVariable(value = "id") Long id) throws ParseException {
        boolean rs = iRepairCourseServicel.deleteMelodyCourseForGrade(id);
        return new Result(rs ? Code.OK : Code.ERROR, rs ? "删除成功" : "删除失败");
    }


    /**
     * 按学员调课前确认
     *
     * @return
     */
    @PostMapping("/melodyCourseForStudentConfirm")
    public Result melodyCourseForStudentConfirm(@RequestBody RepairCourse repairCourse) {
        CourseSchedulingDetail outCourseSchedulingDetail = iCourseSchedulingDetailService.getById(repairCourse.getOutSchedulingDetailId());// 原本的排课详情
        if (outCourseSchedulingDetail.getLessonType().equals(2) || outCourseSchedulingDetail.getLessonType().equals(3)) {
            //非超级管理员刷题班、智能课，只能往前调课
            if (!adminId.equals(1568138350324350975L)) {
                // 判断排课时间是否已经超过原本的排课时间
                if (repairCourse.getSchoolDate().isAfter(outCourseSchedulingDetail.getSchoolDate()) || (repairCourse.getSchoolDate().isEqual(outCourseSchedulingDetail.getSchoolDate()) && repairCourse.getTimeStart().compareTo(outCourseSchedulingDetail.getTimeStart()) >= 0)) {
                    // return new Result(Code.ERROR, "", "上课时间不能大于调出课程的上课时间");
                }
            }
        }
        MelodyConfirm melodyConfirm = iRepairCourseServicel.melodyCourseForStudentConfirm(repairCourse, this.adminId);
        return new Result(Code.OK, melodyConfirm, "");
    }

    /**
     * 按学员调课
     *
     * @param repairCourse
     * @return
     * @throws ParseException
     */
    @PostMapping("/melodyCourseForStudent")
    @RepeatSubmit(expireSeconds = 5)
    public Result melodyCourseForStudent(@RequestBody RepairCourse repairCourse) throws ParseException {

        LocalDateTime dateTimeNow = LocalDateTime.now().withNano(0);

        MelodyConfirm melodyConfirm = iRepairCourseServicel.melodyCourseForStudentConfirm(repairCourse, this.adminId);
        if (melodyConfirm.getStatus().equals(0)) {
            return new Result(Code.ERROR, melodyConfirm, melodyConfirm.getMsg());
        }

        //Long id = courseSchedulingDetailParam.getId();
        CourseSchedulingDetail outCourseSchedulingDetail = iCourseSchedulingDetailService.getById(repairCourse.getOutSchedulingDetailId());// 原本的排课详情
        if (outCourseSchedulingDetail.getEndDateTime().isBefore(dateTimeNow)) {
            //是否存在节假日
            Integer isAt = holidayMapper.getIsAt(outCourseSchedulingDetail.getSchoolDate(), 1);
            //不属于节假日并且不是暂停状态的排课，不能调课
            if (isAt.equals(0) && !outCourseSchedulingDetail.getStatus().equals(2)) {
                //不是节假日，并且不是超级管理员操作
                if (isSuper != 1) {
                    return new Result(Code.ERROR, "", "被调出排课下课时间已过，不能调出");
                }
            }
            for (Long studentId : repairCourse.getStudentIdList()) {
                if (outCourseSchedulingDetail.getLessonNum() != null && outCourseSchedulingDetail.getSubjectsId() != null) {
                    Integer lackCount = iLackCourseLogService.getLackCourseForNum(outCourseSchedulingDetail.getYearPart(), outCourseSchedulingDetail.getQuarter(), studentId, outCourseSchedulingDetail.getSubjectsId(), outCourseSchedulingDetail.getLessonNum(), outCourseSchedulingDetail.getLessonType());
                    if (lackCount > 0) {
                        Student student = iStudentService.getById(studentId);
                        return new Result(Code.ERROR, "", student.getName() + "学生第" + outCourseSchedulingDetail.getLessonNum() + "次课，存在缺课，请到缺课里面安排补课");
                    }
                }
            }
        }

        if (outCourseSchedulingDetail.getLessonType().equals(2) || outCourseSchedulingDetail.getLessonType().equals(3)) {
            //非超级管理员刷题班、智能课，只能往前调课
            if (!adminId.equals(1568138350324350975L)) {
                // 判断排课时间是否已经超过原本的排课时间
                if (repairCourse.getSchoolDate().isAfter(outCourseSchedulingDetail.getSchoolDate()) || (repairCourse.getSchoolDate().isEqual(outCourseSchedulingDetail.getSchoolDate()) && repairCourse.getTimeStart().compareTo(outCourseSchedulingDetail.getTimeStart()) >= 0)) {
                    // return new Result(Code.ERROR, "", "上课时间不能大于调出课程的上课时间");
                }
            }
        }


        Integer lessonType = 1;
        String startDateTime = null;
        String endDateTime = null;
        if (repairCourse.getSchedulingDetailId() != null) {
            CourseSchedulingDetail courseSchedulingDetail = iCourseSchedulingDetailService.getById(repairCourse.getSchedulingDetailId());
            if (courseSchedulingDetail != null) {
                startDateTime = courseSchedulingDetail.getStartDateTime().toString();
                endDateTime = courseSchedulingDetail.getEndDateTime().toString();
            } else {
                startDateTime = repairCourse.getSchoolDate() + "T" + repairCourse.getTimeStart() + ":00";
                endDateTime = repairCourse.getSchoolDate() + "T" + repairCourse.getTimeEnd() + ":00";
            }
        } else {
            startDateTime = repairCourse.getSchoolDate() + "T" + repairCourse.getTimeStart() + ":00";
            endDateTime = repairCourse.getSchoolDate() + "T" + repairCourse.getTimeEnd() + ":00";
        }


        LocalDateTime endDateTimeFormat = LocalDateTime.parse(endDateTime);
        if (endDateTimeFormat.isBefore(dateTimeNow)) {
            return new Result(Code.ERROR, "", "下课时间不能小于当前时间");
        }


        if (melodyConfirm.getType().equals(1)) {
            repairCourse.setUseLeaveNum(1);
        }


        Long count = 0L;
        //Long endCount = 0L;
        String studentName = null;

        QueryWrapper<RepairCourse> repairCourseQueryWrapper = new QueryWrapper<>();
        repairCourseQueryWrapper.eq("scheduling_detail_id", repairCourse.getSchedulingDetailId());
        repairCourseQueryWrapper.eq("student_id", repairCourse.getStudentId());
        count = iRepairCourseServicel.count(repairCourseQueryWrapper);
        if (count > 0) {
            return new Result(Code.ERROR, "", "已安排调课，不能重复操作");
        }
        count = 0L;

        String studentIdStr = repairCourse.getStudentIdList().stream().map(Object::toString).collect(Collectors.joining(","));

        //是否与精品课排课冲突
        List<SchedulingClash> schedulingClashList = iCourseSchedulingDetailService.schedulingClash(outCourseSchedulingDetail.getYearPart(), outCourseSchedulingDetail.getQuarter(), outCourseSchedulingDetail.getSchoolId(), studentIdStr, startDateTime, endDateTime, lessonType.toString(), "");

        StringBuilder studentClashBuilder = new StringBuilder();
        for (SchedulingClash schedulingClash : schedulingClashList) {
            String schoolTime = schedulingClash.getTimeStart() + "-" + schedulingClash.getTimeEnd();
            String courseTypeName = CommonUtil.getCourseTypeName(schedulingClash.getCourseType());
            studentClashBuilder.append(schedulingClash.getStudentName()).append("与").append(courseTypeName).append(schoolTime);
            if (StringUtils.isNotBlank(schedulingClash.getGradeName())) {
                studentClashBuilder.append(",").append(schedulingClash.getGradeName());
            }
            studentClashBuilder.append("存在时间冲突");
            studentClashBuilder.append("；");
        }
        String studentClash = studentClashBuilder.toString();
        if (StringUtils.isNotBlank(studentClash)) {
            return new Result(Code.ERROR, "", studentClash);
        }

        QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
        recordCourseQueryWrapper.eq("scheduling_detail_id", repairCourse.getOutSchedulingDetailId());
        recordCourseQueryWrapper.in("student_id", repairCourse.getStudentIdList());
        List<RecordCourse> recordCourseList = recordCourseMapper.selectList(recordCourseQueryWrapper);
        List<String> rsStuNameList = new ArrayList<>();
        for (RecordCourse recordCourse : recordCourseList) {
            String statusStr = "已签到";
            if (recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                statusStr = "已到课";
            } else if (recordCourse.getStatus().equals(StatusRecordEnum.LEAVE)) {
                statusStr = "已请假";
            } else if (recordCourse.getStatus().equals(StatusRecordEnum.Truancy)) {
                statusStr = "已旷课";
            }
            rsStuNameList.add(recordCourse.getStudentName() + statusStr);
        }
        if (rsStuNameList.size() > 0) {
            return new Result(Code.ERROR, "", String.join(",", rsStuNameList) + "不能调课");
        }

        iRepairCourseServicel.melodyCourseForStudent(repairCourse);
        return new Result(Code.OK);
    }

    /**
     * 消课
     *
     * @param repairCourse
     * @return
     */
    @PostMapping("/consumeCourse")
    public Result consumeCourse(@RequestBody RepairCourse repairCourse) throws ParseException {

        Quarter quarterNow = iQuarterService.getNowQuarter();

        OrderDetail orderDetail = iOrderDetailService.getById(repairCourse.getOrderDetailId());

        if (orderDetail == null) {
            return new Result(Code.ERROR, "", "订单id不能为空");
        }
        if (repairCourse.getStudentIdList().size() == 0) {
            return new Result(Code.ERROR, "", "studentIdList不能为空");
        }

        Integer lessonType = 1;

        String startDateTime = repairCourse.getSchoolDate() + " " + repairCourse.getTimeStart() + ":00";
        String endDateTime = repairCourse.getSchoolDate() + " " + repairCourse.getTimeEnd() + ":00";

        StringBuilder studentClashBuilder = new StringBuilder();

        List<Long> studentIdList = new ArrayList<>();
        for (Long studentId : repairCourse.getStudentIdList()) {
            studentIdList.add(studentId);
        }
        String studentIdStr = studentIdList.stream().map(Object::toString).collect(Collectors.joining(","));

        //是否与精品课排课冲突
        List<SchedulingClash> schedulingClashList = iCourseSchedulingDetailService.schedulingClash(quarterNow.getYearPart(), quarterNow.getNum(), orderDetail.getSchoolId(), studentIdStr, startDateTime, endDateTime, lessonType.toString(), "");
        for (SchedulingClash schedulingClash : schedulingClashList) {
            String schoolTime = schedulingClash.getTimeStart() + "-" + schedulingClash.getTimeEnd();
            String courseTypeName = CommonUtil.getCourseTypeName(schedulingClash.getCourseType());
            studentClashBuilder.append(schedulingClash.getStudentName()).append("与").append(courseTypeName).append(schoolTime);
            if (StringUtils.isNotBlank(schedulingClash.getGradeName())) {
                studentClashBuilder.append(",").append(schedulingClash.getGradeName());
            }
            studentClashBuilder.append("存在时间冲突");
            studentClashBuilder.append("；");
        }

        String studentClash = studentClashBuilder.toString();
        if (StringUtils.isNotBlank(studentClash)) {
            return new Result(Code.ERROR, "", studentClash);
        }

        iRepairCourseServicel.consumeCoruse(repairCourse);
        return new Result(Code.OK);
    }

    /**
     * 调课按班级查看
     *
     * @param pageNum
     * @param pageSize
     * @param startDate
     * @param endDate
     * @param yearPart
     * @param quarterNum
     * @param lessonType
     * @param schoolId
     * @param subjectsId
     * @param courseId
     * @param gradeId
     * @param teacherId
     * @return
     */
    @GetMapping("/consumeCourseForGradeList")
    public Result consumeCourseForGradeList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                            @RequestParam(value = "startDate") String startDate,
                                            @RequestParam(value = "endDate") String endDate,
                                            @RequestParam(value = "yearPart", required = false) String yearPart,
                                            @RequestParam(value = "quarterNum", required = false) String quarterNum,
                                            @RequestParam(value = "lessonType") String lessonType,
                                            @RequestParam(value = "schoolId") String schoolId,
                                            @RequestParam(value = "subjectsId") String subjectsId,
                                            @RequestParam(value = "courseId") String courseId,
                                            @RequestParam(value = "gradeId") String gradeId,
                                            @RequestParam(value = "teacherId") String teacherId) {

        IPage<CourseSchedulingDetail> iPage = new Page<>(pageNum, pageSize);

        QueryWrapper<CourseSchedulingDetail> courseSchedulingDetailQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            courseSchedulingDetailQueryWrapper.between("school_date", startDate, endDate);
        } else if (StringUtils.isNotBlank(startDate)) {
            courseSchedulingDetailQueryWrapper.ge("school_date", startDate);
        } else if (StringUtils.isNotBlank(endDate)) {
            courseSchedulingDetailQueryWrapper.le("school_date", endDate);
        }
        if (StringUtils.isNotBlank(schoolId)) {
            courseSchedulingDetailQueryWrapper.eq("school_id", schoolId);
        } else {
            courseSchedulingDetailQueryWrapper.in("school_id", this.baseSchoolIdList);
        }
        courseSchedulingDetailQueryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        courseSchedulingDetailQueryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter", quarterNum);
        courseSchedulingDetailQueryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);
        courseSchedulingDetailQueryWrapper.inSql(StringUtils.isNotBlank(courseId), "grade_id", "select id from grade where course_id = " + courseId + " ");
        courseSchedulingDetailQueryWrapper.eq(StringUtils.isNotBlank(gradeId), "grade_id", gradeId);
        courseSchedulingDetailQueryWrapper.eq(StringUtils.isNotBlank(teacherId), "teacher_id", teacherId);
        courseSchedulingDetailQueryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);
        courseSchedulingDetailQueryWrapper.eq("type", 2);
        courseSchedulingDetailQueryWrapper.eq("deleted", 0);

        if (this.sourseLeve.equals(2)) {
            courseSchedulingDetailQueryWrapper.eq("teacher_id", this.adminId);
        }

        courseSchedulingDetailQueryWrapper.orderByDesc("pid", "id");
        iCourseSchedulingDetailService.calendarList(iPage, courseSchedulingDetailQueryWrapper);

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    /**
     * 调课/消课，按学员查看
     *
     * @param pageNum
     * @param pageSize
     * @param startDate
     * @param endDate
     * @param yearPart
     * @param quarterNum
     * @param lessonType
     * @param schoolId
     * @param subjectsId
     * @param courseId
     * @param courseType
     * @param gradeId
     * @param teacherId
     * @param studentName
     * @return
     */
    @GetMapping("/consumeCourseForStudentList")
    public Result consumeCourseForStudentList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                              @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                              @RequestParam(value = "startDate") String startDate,
                                              @RequestParam(value = "endDate") String endDate,
                                              @RequestParam(value = "yearPart", required = false) String yearPart,
                                              @RequestParam(value = "quarterNum", required = false) String quarterNum,
                                              @RequestParam(value = "lessonType") String lessonType,
                                              @RequestParam(value = "schoolId") String schoolId,
                                              @RequestParam(value = "subjectsId") String subjectsId,
                                              @RequestParam(value = "courseId") String courseId,
                                              @RequestParam(value = "courseType") String courseType,
                                              @RequestParam(value = "gradeId") String gradeId,
                                              @RequestParam(value = "teacherId") String teacherId,
                                              @RequestParam(value = "studentName") String studentName
    ) {
        IPage<RecordCourse> iPage = new Page<>(pageNum, pageSize);

        QueryWrapper<RecordCourse> repairCourseQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            repairCourseQueryWrapper.between("school_date", startDate, endDate);
        } else if (StringUtils.isNotBlank(startDate)) {
            repairCourseQueryWrapper.ge("school_date", startDate);
        } else if (StringUtils.isNotBlank(endDate)) {
            repairCourseQueryWrapper.le("school_date", endDate);
        }

        if (StringUtils.isNotBlank(schoolId)) {
            repairCourseQueryWrapper.eq("school_id", schoolId);
        } else {
            repairCourseQueryWrapper.in("school_id", this.baseSchoolIdList);
        }
        repairCourseQueryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);


        repairCourseQueryWrapper.eq("deleted", 0);
        repairCourseQueryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        repairCourseQueryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter", quarterNum);
        repairCourseQueryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);
        repairCourseQueryWrapper.inSql(StringUtils.isNotBlank(courseId), "grade_id", "select id from grade where course_id = " + courseId + " ");
        repairCourseQueryWrapper.inSql(StringUtils.isNotBlank(studentName), "student_id", "select id from student where name like '%" + studentName + "%' ");
        repairCourseQueryWrapper.eq(StringUtils.isNotBlank(gradeId), "old_grade_id", gradeId);
        repairCourseQueryWrapper.eq(StringUtils.isNotBlank(teacherId), "teacher_id", teacherId);
        if (StringUtils.isNotBlank(courseType)) {
            repairCourseQueryWrapper.eq("course_type", courseType);
        } else {
            repairCourseQueryWrapper.in("course_type", 4, 5);
        }
        if (this.sourseLeve.equals(2)) {
            repairCourseQueryWrapper.eq("teacher_id", this.adminId);
        }

        repairCourseQueryWrapper.orderByDesc("id");

        iRepairCourseServicel.consumeCourseForStudentList(iPage, repairCourseQueryWrapper);
        //iCourseSchedulingDetailService.calendarList(iPage,repairCourseQueryWrapper);

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }


    /**
     * 按学员查看
     *
     * @param id
     * @return
     */
    @GetMapping("/switchingDetail")
    public Result switchingDetail(@RequestParam(value = "id", defaultValue = "") String id) {

        if (StringUtils.isBlank(id)) {
            return new Result(Code.ERROR, "", "id不能为空");
        }
        RepairCourse repairCourse = iRepairCourseServicel.getById(id);
        if (repairCourse == null) {
            return new Result(Code.ERROR, "", "调课数据不存在");
        }
        CourseSchedulingDetail courseSchedulingDetail = iCourseSchedulingDetailService.getCourseSchedulingDetailById(repairCourse.getOutSchedulingDetailId());
        if (courseSchedulingDetail == null) {
            return new Result(Code.ERROR, "", "没有找到被调课数据");
        }

        return new Result(Code.OK, courseSchedulingDetail, "获取成功");
    }


    /**
     * 按班级查看
     *
     * @param id
     * @return
     */
    @GetMapping("/switchingDetailByGrade")
    public Result switchingDetailByGrade(@RequestParam(value = "id", defaultValue = "") String id) {

        CourseSchedulingDetail courseSchedulingDetail = iCourseSchedulingDetailService.getById(id);
        if (courseSchedulingDetail == null) {
            return new Result(Code.ERROR, "", "没有找到调课数据");
        }

        CourseSchedulingDetail courseSchedulingDetailInfo = iCourseSchedulingDetailService.getCourseSchedulingDetailById(courseSchedulingDetail.getPid());
        if (courseSchedulingDetailInfo == null) {
            return new Result(Code.ERROR, "", "没有找到被调课数据");
        }

        return new Result(Code.OK, courseSchedulingDetailInfo, "获取成功");
    }

    /**
     * @return
     */
    @DeleteMapping("/deleteConsumeCourse/{id}")
    public Result deleteConsumeCourse(@PathVariable(value = "id") Long id) {
        RepairCourse repairCourse = iRepairCourseServicel.getById(id);
        if (repairCourse == null) {
            return new Result(Code.ERROR, "", "数据不存在");
        }
        if (repairCourse.getStatus().equals(1)) {
            return new Result(Code.ERROR, "", "已上课，不能删除");
        }

        //1精品课（正常排课），3补课，4调课，5消课
        if (repairCourse.getCourseType().equals(4)) {
            CourseSchedulingDetail courseSchedulingDetail = iCourseSchedulingDetailService.getById(repairCourse.getOutSchedulingDetailId());
            LocalDateTime dateTimeNow = LocalDateTime.now().withNano(0);
            if (courseSchedulingDetail != null && dateTimeNow.isAfter(courseSchedulingDetail.getEndDateTime()) && !courseSchedulingDetail.getStatus().equals(StatusSchedulingEnum.STOP)) {
                return new Result(Code.ERROR, "", "当前时间已经大于被调出的排课下课时间，不能删除");
            }
        }

        //学生已经签到上课
        if (repairCourse.getIsSignIn().equals(1)) {
            RecordCourse recordCourseNew = recordCourseMapper.selectOne(new QueryWrapper<RecordCourse>().eq("scheduling_detail_id", repairCourse.getId()).last("limit 1"));
            if (recordCourseNew != null) {
                return new Result(Code.ERROR, null, "学生已经签到上课，不能删除");
            }
        }

        iRepairCourseServicel.removeById(id);
        return new Result(Code.OK, "", "删除成功");
    }


    /**
     * 添加到课
     *
     * @param repairCourseParam
     * @return
     */
    @PostMapping("/arriveClass")
    public Result arriveClass(@RequestBody RepairCourse repairCourseParam) {

        LocalDateTime dateTimeNow = LocalDateTime.now().withNano(0);
        RepairCourse repairCourse = iRepairCourseService.getById(repairCourseParam.getId());
        Student student = iStudentService.getById(repairCourse.getStudentId());

        iRecordCourseService.addForSchedulingId(repairCourse.getId(), repairCourse.getStudentId(), student.getName(), 1, repairCourse.getCourseType(), ReachTypeEnum.NORMAL, null, dateTimeNow, 2, "");
        //补、调、消课、缺课补课改为到课状态
        if (repairCourse.getCourseType() != null) {
            if (repairCourse.getCourseType() == 3 || repairCourse.getCourseType() == 4 || repairCourse.getCourseType() == 5 || repairCourse.getCourseType() == 6) {
                repairCourse.setIsSignIn(1);
                iRepairCourseService.updateById(repairCourse);
            }
        }
        return new Result(Code.OK, "", "添加成功");
    }


    /**
     * 添加临时排班
     */
    @PostMapping("/saveTemporaryClass")
    public Result saveTemporaryClass(@RequestBody RepairCourse repairCourseParam) {
        if (repairCourseParam.getGradeId() == null) {
            return new Result(Code.ERROR, "", "请选择班级");
        }

        Grade grade = gradeMapper.selectById(repairCourseParam.getGradeId());
        Long oldTeacherId = grade.getTeacherId();
        String gradeName = grade.getName();
        Long gradeId = grade.getId();
        Long subjectsId = grade.getSubjectsId();
        Long schoolId = grade.getSchoolId();
        Integer yearClassId = grade.getYearClassId().getKey();

        String subjectsName = CommonUtil.getSubjectsNameForId(Math.toIntExact(subjectsId));
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        Long studentId = repairCourseParam.getStudentId();
        Long teacherId = repairCourseParam.getTeacherId();
        String teacherName = repairCourseParam.getTeacherName();
        Long roomId = repairCourseParam.getRoomId();
        String roomName = repairCourseParam.getRoomName();
        Integer lessonType = repairCourseParam.getLessonType(); // 1精品课
        Integer courseType = repairCourseParam.getCourseType(); // 9临时排课

        LocalDateTime nowDateTime = LocalDateTime.now().withNano(0);


    /*    for (RepairCourse repairCourse : repairCourseParam.getSchoolTimeList()) {
            // 判断时间点是否有冲突（临时排班只跟精品课冲突）
            if (this.isSuper != 1) {
                Quarter quarterForYearAndNum = iQuarterService.getQuarterForYearAndNum(grade.getYearPart(), grade.getQuarterNum());

                LocalDateTime startDateTime = LocalDateTime.parse(repairCourse.getSchoolDate() + " " + repairCourse.getTimeStart(), formatter);
                LocalDateTime endDateTime = LocalDateTime.parse(repairCourse.getSchoolDate() + " " + repairCourse.getTimeEnd(), formatter);

                //学期班
                if (quarterForYearAndNum.getType().equals(1)) {
                    //非周末
                    // 获取排课日期的星期
                    DayOfWeek dayOfWeek = repairCourse.getSchoolDate().getDayOfWeek();
                    System.err.println("dayOfWeek" + dayOfWeek.getValue());
                    if (!(dayOfWeek.getValue() == 6) && !(dayOfWeek.getValue() == 7)) {
                        String planGradeName = iStudentGradeService.getWeekDatesPlanGradeByLessonType(grade.getYearPart(), grade.getQuarterNum(), studentId, String.valueOf(dayOfWeek.getValue()), 1);
                        if (StringUtils.isNotBlank(planGradeName)) {
                            return new Result(Code.ERROR, "", CommonUtil.getWeekForId(Integer.parseInt(String.valueOf(dayOfWeek.getValue()))) + "已排：" + planGradeName + ",添加失败");
                        }
                    } else {
                        //周末
                        List<String> stringList = new ArrayList<>();
                        String clashStr = "";
                        List<RepairCourse> repairCourseList = iCourseSchedulingDetailService.getSchedulingClashByLessonType(grade.getYearPart(), grade.getQuarterNum(), studentId, gradeId, nowDateTime.toString(), 1, startDateTime, endDateTime);
                        if (repairCourseList.size() > 0) {
                            Student student = iStudentService.getById(studentId);
                            for (RepairCourse repairCourse1 : repairCourseList) {
                                clashStr = student.getName() + "," + repairCourse1.getGradeName() + "" + repairCourse1.getSchoolDate() + " " + repairCourse1.getTimeStart() + " " + repairCourse1.getTimeEnd();
                                stringList.add(clashStr);
                            }
                        }
                        if (stringList.size() > 0) {
                            StringBuilder studentBuilder = new StringBuilder();
                            studentBuilder.append("存在时间冲突:" + String.join(",", stringList));
                            return new Result(Code.ERROR, stringList, studentBuilder.toString());
                        }
                    }
                } else {
                    //假期班
                    List<String> stringList = new ArrayList<>();
                    String clashStr = "";
                    List<RepairCourse> repairCourseList = iCourseSchedulingDetailService.getSchedulingClashByLessonType(grade.getYearPart(), grade.getQuarterNum(), studentId, gradeId, nowDateTime.toString(), 1, startDateTime, endDateTime);
                    if (repairCourseList.size() > 0) {
                        Student student = iStudentService.getById(studentId);
                        for (RepairCourse repairCourse1 : repairCourseList) {
                            clashStr = student.getName() + "," + repairCourse1.getGradeName() + "" + repairCourse1.getSchoolDate() + " " + repairCourse1.getTimeStart() + " " + repairCourse1.getTimeEnd();
                            stringList.add(clashStr);
                        }
                    }
                    if (stringList.size() > 0) {
                        StringBuilder studentBuilder = new StringBuilder();
                        studentBuilder.append("存在时间冲突:" + String.join(",", stringList));
                        return new Result(Code.ERROR, stringList, studentBuilder.toString());
                    }
                }
            }
        }*/

        for (RepairCourse repairCourse : repairCourseParam.getSchoolTimeList()) {
            RepairCourse repairCourseNew = new RepairCourse();
            repairCourseNew.setSchoolId(schoolId);
            repairCourseNew.setStudentId(studentId);
            repairCourseNew.setGradeId(gradeId);
            repairCourseNew.setGradeName(gradeName);
            repairCourseNew.setOldGradeId(gradeId);
            repairCourseNew.setOldTeacherId(oldTeacherId);
            repairCourseNew.setSchoolDate(repairCourse.getSchoolDate());
            repairCourseNew.setTimeStart(repairCourse.getTimeStart());
            repairCourseNew.setTimeEnd(repairCourse.getTimeEnd());
            repairCourseNew.setStartDateTime(LocalDateTime.parse(repairCourse.getSchoolDate() + " " + repairCourse.getTimeStart(), formatter));
            repairCourseNew.setEndDateTime(LocalDateTime.parse(repairCourse.getSchoolDate() + " " + repairCourse.getTimeEnd(), formatter));
            repairCourseNew.setTeacherId(teacherId);
            repairCourseNew.setTeacherName(teacherName);
            repairCourseNew.setRoomId(roomId);
            repairCourseNew.setRoomName(roomName);
            repairCourseNew.setLessonType(lessonType);
            repairCourseNew.setSubjectsId(subjectsId);
            repairCourseNew.setSubjectsName(subjectsName);
            repairCourseNew.setCourseType(courseType);
            repairCourseNew.setYearClassId(yearClassId);

            Quarter quarter = iQuarterService.getQuarterByDate(repairCourse.getSchoolDate());
            if (quarter != null) {
                repairCourseNew.setYearPart(quarter.getYearPart());
                repairCourseNew.setQuarter(quarter.getNum());
            }

            iRepairCourseService.save(repairCourseNew);
        }

        return new Result(Code.OK, "", "添加成功");
    }


    /**
     * 获取临时排班
     */
    @GetMapping("/getTemporaryClass")
    public Result getTemporaryClass(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                    @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                    @RequestParam(value = "courseType", defaultValue = "9") Integer courseType,
                                    @RequestParam(value = "yearPart", required = false) String yearPart,
                                    @RequestParam(value = "quarterNum", required = false) String quarterNum,
                                    @RequestParam(value = "schoolId", required = false) String schoolId,
                                    @RequestParam(value = "subjectsId", required = false) String subjectsId,
                                    @RequestParam(value = "startDate", defaultValue = "") String startDate,
                                    @RequestParam(value = "endDate", defaultValue = "") String endDate,
                                    @RequestParam(value = "teacherId", defaultValue = "") String teacherId,
                                    @RequestParam(value = "courseId", defaultValue = "") String courseId,
                                    @RequestParam(value = "studentName", defaultValue = "") String studentName) {

        IPage<RepairCourse> iPage = new Page<>(pageNum, pageSize);

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("t1.deleted", 0);
        queryWrapper.eq("course_type", courseType);
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "t1.year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "t1.quarter", quarterNum);
        queryWrapper.like(StringUtils.isNotBlank(studentName), "t4.`name`", studentName);
        queryWrapper.eq(StringUtils.isNotBlank(teacherId), "t1.teacher_id", teacherId);
        queryWrapper.inSql(StringUtils.isNotBlank(schoolId), "t1.school_id", schoolId);
        queryWrapper.inSql(StringUtils.isNotBlank(courseId), "t3.id", courseId);
        queryWrapper.inSql(StringUtils.isNotBlank(subjectsId), "t1.subjects_id", subjectsId);
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            queryWrapper.between("school_date", startDate, endDate);
        }
        queryWrapper.orderByDesc("t1.id");

        iRepairCourseService.getTemporaryClass(iPage, queryWrapper);

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    /**
     * 删除临时排班
     */
    @DeleteMapping("/delTemporaryClass")
    public Result delTemporaryClass(@RequestParam(value = "id") String id) {
        RepairCourse repairCourse = iRepairCourseService.getById(id);
        if (repairCourse == null) {
            return new Result(Code.ERROR, "", "该临时排班不存在");
        }

        // 判断该日程是否已经上过课
        if (repairCourse.getStatus() == 1 || repairCourse.getIsSignIn() == 1) {
            return new Result(Code.ERROR, "", "该日程已上课，无法删除");
        }

        // 判断该日程是否已过期
        if (repairCourse.getEndDateTime().isBefore(LocalDateTime.now())) {
            return new Result(Code.ERROR, "", "该日程已过期，无法删除");
        }

        iRepairCourseService.removeById(id);

        return new Result(Code.OK, "", "删除成功");
    }

}

